/**
 * Created by tanbingqin on 2020/6/11.
 */
import moment from 'moment';
import { messages } from 'share/common';

export default {
  //处理控件池初始数据
  processWidgetListData(widgetList, isCombine) {
    widgetList && widgetList.forEach(item => {
      item.fieldConstraint = item.constraintRule;
      item.readonly = !item.deleted;
      item.fieldName = item.name;
      item.hide = item.hideEnabled;
      item.isCombine = isCombine;
      item.subWidgetList && item.subWidgetList.length && item.subWidgetList.forEach(subItem => {
        subItem.fieldConstraint = subItem.constraintRule;
        subItem.fieldName = subItem.name;
        subItem.hide = subItem.hideEnabled;
      });
    });
  },

  /**
   * 初始化处理表单控件数据
   * @param customFormFields
   * @param formCombineWidget 套件控件
   * @param languageList
   * @param currentLanguage
   */
  initNowWidget(customFormFields, formCombineWidget, languageList, currentLanguage) {
    let nowWidget = customFormFields ? JSON.parse(JSON.stringify(customFormFields)) : [];
    let combineWidget = formCombineWidget ? JSON.parse(JSON.stringify(formCombineWidget)) : [];

    //处理控件多语言
    nowWidget = this.processLanguage(nowWidget, languageList, currentLanguage);

    //处理系统控件下的开始结束日期
    nowWidget = this.processStartEndDate(nowWidget, false);

    //处理套件 1.套件组件的合并 2.套件里的开始结束日期合并 3.套件不启用的没有，则要从控件池里拼进去
    //处理套件控件下的开始结束日期
    nowWidget = this.processStartEndDate(nowWidget, true);

    let suiteFirstIndex = 0; //套件子组件第一个的index，这是拼装成套件后插入的index
    let guiWidgetOID = ''; //根据这个oid识别是哪一个套件
    let i = 0;
    let length = nowWidget.length;
    for (i; i < length; i++) {
      if (nowWidget[i].guiWidgetOID) {
        suiteFirstIndex = i;
        guiWidgetOID = nowWidget[i].guiWidgetOID;
        break;
      }
    }

    let suiteList = nowWidget.filter(item => item.guiWidgetOID);
    let suiteWidget = this.processSuite(combineWidget, guiWidgetOID, suiteList);
    nowWidget = nowWidget.filter(item => !item.guiWidgetOID);
    suiteWidget.messageKey && nowWidget.splice(suiteFirstIndex, 0, suiteWidget);

    //给nowWidget里的每个控件给个id标识
    //counterFlag为内部组件排序所需key值，在此处初始化
    //要等前面控件处理完毕后初始化
    nowWidget.forEach((widget, index) => {
      widget.counterFlag = index;
    });
    return nowWidget;
  },

  /**
   * 处理套件组件 直接返回一个拼装好的套件组件
   * @param combineWidget 套件控件
   * @param guiWidgetOID 套件识别oid
   * @param suiteList 当前表单配置的启用的套件子组件列表
   */
  processSuite(combineWidget, guiWidgetOID, suiteList) {
    let suiteWidget = {
      isCombine: true,
      guiWidgetOID,
    };
    let subWidgetList = [];
    combineWidget && combineWidget.forEach(suite => {
      if (suite.guiWidgetOID === guiWidgetOID) {
        suiteWidget.messageKey = suite.messageKey;
        suiteWidget.fieldName = suite.name;
        subWidgetList = suite.subWidgetList;
      }
    });
    subWidgetList.forEach((subWidget, subIndex) => {
      //判断当前表单配置中是否存在子组件，如果存在则要替换
      let isExist = false;
      let tempWidget = null;
      suiteList && suiteList.forEach(item => {
        if (subWidget.messageKey === item.messageKey) {
          isExist = true;
          tempWidget = item;
        }
      });
      if (isExist) {
        //subWidget = tempWidget; 该写法有误，subWidget是forEach里新的变量，该写法只是改写新的变量指向，并不能修改原数据
        subWidgetList[subIndex] = tempWidget;
      }
    });
    suiteWidget.subWidgetList = subWidgetList;
    return suiteWidget;
  },

  //编辑状态初始化每个已有控件的多语言
  processLanguage(nowWidget, languageList, currentLanguage) {
    let resultList = JSON.parse(JSON.stringify(nowWidget));
    resultList.forEach((widget, index) => {
      if (!widget.i18n) {
        widget.i18n = {};
      }
      if (!widget.i18n.fieldName || !widget.i18n.fieldName.length) {
        let fieldNameI18n = [];
        languageList.forEach(language => {
          let i18nDTO = {
            language: language.code,
            value: language.code.toLowerCase() === currentLanguage.code.toLowerCase() ? widget.fieldName : ''
          };
          fieldNameI18n.push(i18nDTO);
        });
        widget.i18n.fieldName = fieldNameI18n;
      }
      if (!widget.i18n.promptInfo || !widget.i18n.promptInfo.length) {
        let promptInfoI18n = [];
        languageList.forEach(language => {
          let i18nDTO = {
            language: language.code,
            value: language.code.toLowerCase() === currentLanguage.code.toLowerCase() ? widget.promptInfo : ''
          };
          promptInfoI18n.push(i18nDTO);
        });
        widget.i18n.promptInfo = promptInfoI18n;
      }
      this.initWidgetI18nByKey(widget, 'fieldNameI18n', 'fieldName', languageList, currentLanguage);
      this.initWidgetI18nByKey(widget, 'promptInfoI18n', 'promptInfo', languageList, currentLanguage);
    });
    return resultList;
  },

  //处理开始结束日期合并，把结束日期控件的数据添加到开始日期控件下，并删除结束日期，把开始日期控件messageKey修改成组合控件的messageKey
  //isSuite 是否是处理套件内的开始结束日期
  processStartEndDate(nowWidget, isSuite) {
    let resultList = JSON.parse(JSON.stringify(nowWidget));
    let startDateIndex = -1;
    let endDateIndex = -1;
    resultList.forEach((widget, index) => {
      //把两个有com_start_date,com_end_date控件拼装成一个com_start_end_date控件
      if(widget.messageKey === 'com_start_date' && ((!isSuite && !widget.guiWidgetOID) || (isSuite && widget.guiWidgetOID))){
        startDateIndex = index;
      }
      if(widget.messageKey === 'com_end_date' && ((!isSuite && !widget.guiWidgetOID) || (isSuite && widget.guiWidgetOID))){
        endDateIndex = index;
      }
    });
    if(startDateIndex > -1 && endDateIndex > -1){
      let startDateWidget = resultList[startDateIndex];
      let endDateWidget = resultList[endDateIndex];
      startDateWidget.subFieldConstraint = endDateWidget.fieldConstraint;
      startDateWidget.subFieldName = endDateWidget.fieldName;
      startDateWidget.subFieldNameI18n = endDateWidget.fieldNameI18n;
      startDateWidget.subFieldCode = endDateWidget.fieldCode;
      startDateWidget.subFieldOID = endDateWidget.fieldOID;
      startDateWidget.subID = endDateWidget.id;
      startDateWidget.subI18n = endDateWidget.i18n;
      startDateWidget.messageKey = 'com_start_end_date';
      startDateWidget.required = startDateWidget.required && endDateWidget.required;
      resultList.splice(endDateIndex, 1);
    }
    return resultList;
  },

  //处理开始结束日期拆分，把结束日期控件的数据添加到开始日期控件下，把开始结束日期控件messageKey修改成单个控件的messageKey
  //isSuite 是否是处理套件内的开始结束日期
  splitStartEndDate(nowWidget, isSuite) {
    let resultList = JSON.parse(JSON.stringify(nowWidget));
    let startEndDateIndex = -1;
    let newWidget = {};
    resultList.forEach((widget, index) => {
      if(widget.messageKey === 'com_start_end_date' && ((!isSuite && !widget.guiWidgetOID) || (isSuite && widget.guiWidgetOID))){
        startEndDateIndex = index;
        widget.messageKey = 'com_start_date';
        widget.dataSource = "";
        widget.fieldType = 'DATE';
        newWidget.messageKey = 'com_end_date';
        newWidget.fieldName = widget.subFieldName;
        newWidget.required = widget.required;
        newWidget.isReadOnly = widget.isReadOnly;
        newWidget.id = widget.subID;
        newWidget.fieldCode = widget.subFieldCode;
        newWidget.fieldOID = widget.subFieldOID;
        newWidget.fieldConstraint = widget.subFieldConstraint;
        newWidget.i18n = {};
        newWidget.fieldNameI18n = widget.subFieldNameI18n;
        newWidget.valid = widget.valid;
        newWidget.dataSource = "";
        newWidget.fieldType = "DATE";
        newWidget.guiWidgetOID = isSuite ? widget.guiWidgetOID : '';
      }
    });
    startEndDateIndex > -1 && resultList.splice(startEndDateIndex + 1, 0, newWidget);
    return resultList;
  },

  //把zh_cn转换成zh_CN
  processLanguageToUpperCase(i18nList) {
    let i18nResultList = JSON.parse(JSON.stringify(i18nList));
    i18nResultList.map(item => {
      if (item.language === 'zh_cn') {
        item.language = 'zh_CN';
      }
    });
    return i18nResultList;
  },

  //把zh_cn转换成zh_cn
  processLanguageToLowerCase(i18nList) {
    let i18nResultList = JSON.parse(JSON.stringify(i18nList));
    i18nResultList.map(item => {
      if (item.language === 'zh_CN') {
        item.language = 'zh_cn';
      }
    });
    return i18nResultList;
  },

  //新拖拽一个控件处理不同字段的i18n初始化值 -- 可以从i18n下赋值的
  initWidgetI18nByKey(widget, key, originKey, languageList, currentLanguage) {
    if (!widget[key]) {
      if (widget.i18n && widget.i18n[originKey]) {
        widget[key] = widget.i18n[originKey];
      } else {
        let i18nList = [];
        languageList.forEach(language => {
          let i18nDTO = {
            language: language.code,
            value: language.code.toLowerCase() === currentLanguage.code.toLowerCase() ? widget[originKey] : ''
          };
          i18nList.push(i18nDTO);
        });
        widget[key] = i18nList;
      }
      widget[key] = this.processLanguageToLowerCase(widget[key]);
    }
  },

  //新拖拽一个控件处理不同字段的i18n初始化值 -- 直接从给定的value赋值的
  initWidgetI18nByValue(widget, key, value, languageList, currentLanguage) {
    if (!widget[key]) {
      let i18nList = [];
      languageList.forEach(language => {
        let i18nDTO = {
          language: language.code,
          value: language.code.toLowerCase() === currentLanguage.code.toLowerCase() ? value : ''
        };
        i18nList.push(i18nDTO);
      });
      widget[key] = i18nList;
      widget[key] = this.processLanguageToLowerCase(widget[key]);
    }
  },

  //获取文本控件可输入字符上限
  getMaxLength(messageKey) {
    let maxLength = 500;
    switch (messageKey) {
      case 'com_remarks':
        maxLength = 500;
        break;
      case 'com_text_area':
        maxLength = 1000;
        break;
    }
    return maxLength
  },

  //是否显示'隐藏'配置
  isShowHide(widget) {
    return widget.hide !== null && widget.hide !== undefined;
  },

  //是否显示'只读'配置
  isShowReadonly(widget) {
    let showMessageKeyList = ['com_company_paid', 'com_room_number'];
    return showMessageKeyList.indexOf(widget.messageKey) > -1;
  },

  //是否不需要提示文字
  isHidePrompt(widget) {
    //这些messageKey的控件不需要提示文字
    let hideMessageKeyList = [
      'com_switch',
      'com_prompt_text',
      'com_start_end_date',
      'com_car'
    ];
    return hideMessageKeyList.indexOf(widget.messageKey) > -1;
  },

  //常用配置字段是否显示，控制字段包括： 标题，编码
  isShowComponent(widget) {
    let hideMessageKeyList = [
      'com_prompt_text',
      'com_car'
    ];
    return !(hideMessageKeyList.indexOf(widget.messageKey) > -1);
  },

  //是否显示'必填'配置
  isShowRequired(widget) {
    let hideMessageKeyList = [
      'com_prompt_text',
      'com_company_paid',
      'com_car'
    ];
    return !(hideMessageKeyList.indexOf(widget.messageKey) > -1);
  },

  //是否显示'启用'配置
  isShowValid(widget) {
    let hideMessageKeyList = [
      'com_car'
    ];
    return !(hideMessageKeyList.indexOf(widget.messageKey) > -1);
  },

  //获取用车配置项
  getCarConfigBase() {
    return [
      {
        key: 'travel',
        name: messages('expense-6.key245')/*差旅用车*/,
        value: false,
        editable: true,
        subConfigList: [
          {
            key: 'carRule',
            name: messages('expense-6.key246')/*用车制度*/,
            show: true,
            required: true,
            showEditable: false,
            requiredEditable: false
          },
          {
            key: 'startEndDate',
            name: messages('expense-6.key235')/*开始结束日期*/,
            show: true,
            required: true,
            showEditable: false,
            requiredEditable: false
          },
          {
            key: 'formCity',
            name: messages('expense-6.key126')/*出发城市*/,
            show: true,
            required: true,
            showEditable: true,
            requiredEditable: true
          },
          {
            key: 'toCity',
            name: messages('expense-6.key127')/*到达城市*/,
            show: true,
            required: true,
            showEditable: true,
            requiredEditable: true
          }
        ]
      },
      {
        key: 'date',
        name: messages('expense-6.key247')/*按日期用车*/,
        value: false,
        editable: true,
        subConfigList: [
          {
            key: 'carRule',
            name: messages('expense-6.key246')/*用车制度*/,
            show: true,
            required: true,
            showEditable: false,
            requiredEditable: false
          },
          {
            key: 'startEndDate',
            name: messages('expense-6.key235')/*开始结束日期*/,
            show: true,
            required: true,
            showEditable: false,
            requiredEditable: false
          },
          {
            key: 'city',
            name: messages('expense-6.key248')/*城市*/,
            show: true,
            required: false,
            showEditable: true,
            requiredEditable: true
          },
          {
            key: 'carStandard',
            name: messages('expense-6.key249')/*标准*/,
            show: true,
            required: false,
            showEditable: true,
            requiredEditable: true
          }
        ]
      },
      {
        key: 'times',
        name: messages('expense-6.key250')/*按次用车*/,
        value: false,
        editable: true,
        subConfigList: [
          {
            key: 'carRule',
            name: messages('expense-6.key246')/*用车制度*/,
            show: true,
            required: true,
            showEditable: false,
            requiredEditable: false
          },
          {
            key: 'startEndDate',
            name: messages('expense-6.key235')/*开始结束日期*/,
            show: true,
            required: true,
            showEditable: false,
            requiredEditable: false
          },
          {
            key: 'useTimes',
            name: messages('expense-6.key251')/*用车次数*/,
            show: true,
            required: true,
            showEditable: false,
            requiredEditable: false
          },
        ]
      },
      {
        key: 'carQuick',
        name: messages('expense-6.key252')/*马上用车*/,
        value: false,
        editable: true,
        subConfigList: [
          {
            key: 'startEndDate',
            name: messages('expense-6.key235')/*开始结束日期*/,
            show: true,
            required: true,
            showEditable: false,
            requiredEditable: false
          },
          {
            key: 'city',
            name: messages('expense-6.key248')/*城市*/,
            show: true,
            required: false,
            showEditable: false,
            requiredEditable: true
          },
          {
            key: 'useTimes',
            name: messages('expense-6.key251')/*用车次数*/,
            show: true,
            required: false,
            showEditable: true,
            requiredEditable: true
          },
          {
            key: 'carStandard',
            name: messages('expense-6.key249')/*标准*/,
            show: true,
            required: false,
            showEditable: true,
            requiredEditable: true
          }
        ]
      },
      {
        key: 'carPickup',
        name: messages('expense-6.key253')/*接送机／火车*/,
        value: false,
        editable: true,
        subConfigList: [
          {
            key: 'startEndDate',
            name: messages('expense-6.key235')/*开始结束日期*/,
            show: true,
            required: false,
            showEditable: false,
            requiredEditable: false
          },
          {
            key: 'city',
            name: messages('expense-6.key248')/*城市*/,
            show: true,
            required: true,
            showEditable: false,
            requiredEditable: false
          },
          {
            key: 'type',
            name: messages('expense-6.key254')/*接送类型*/,
            show: true,
            required: true,
            showEditable: false,
            requiredEditable: false
          }
        ]
      }
    ]
  },

  //校验控件标题是否填写
  validateFieldName(widget) {
    let isOk = true;
    let ignoreList = ['com_prompt_text', 'com_car'];
    if (ignoreList.indexOf(widget.messageKey) === -1) {
      if (!widget.fieldName || (widget.messageKey === 'com_start_end_date' && !widget.subFieldName)) {
        isOk = false;
      }
    }
    return isOk;
  },
}
